<template>
  <div class="art-full-height">
    <!-- 搜索栏 (等待后端修改) -->
    <ArtSearchBar
      v-model="searchForm"
      :items="formItems"
      :show-expand="true"
      @search="handleSearch"
      @reset="handleResetSearch"
    />

    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader
        v-model:columns="columnChecks"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
      </ArtTableHeader>

      <!-- 数据表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
        <template #operation="{ row }">
          <div class="flex justify-center gap-2">
            <ArtButtonTable
              type="view"
              title="查看"
              @click="handleView(row)"
            />
          </div>
        </template>
      </ArtTable>
    </ElCard>
    
    <!-- 查看详情弹窗 -->
    <HelpViewDialog
      :key="dialogKey"
      :model-value="detailVisible"
      :detail-data="currentRow"
      @update:model-value="handleDialogUpdate"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, h } from 'vue'
  import { ElMessage } from 'element-plus'
  import { useTable } from '@/composables/useTable'
  import ArtSearchBar from '@/components/core/forms/art-search-bar/index.vue'
  import ArtTable from '@/components/core/tables/art-table/index.vue'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import { DictTag } from '@/components/core/dics/index.vue'
  import {
    recordUserAreaHelpPageDataUsingPost as pageDataApi,
    recordUserAreaHelpGetDataUsingPost as getDataApi,
    openApiNewUserPageDataUsingPost,
    apiEmployeeGetPageUsingPost,
    geoAreaPageDataUsingPost
  } from '@/api'
  import type { RecordUserAreaHelpVo } from '@/api/types'
  import HelpViewDialog from './list/help-view-dialog.vue'

  // 类型定义
  interface SearchForm {
    newPhone: string
    employeeName: string
    areaName: string
    recordSolveStatus: string | undefined
    createTime: [string, string] | undefined
    userId: number | undefined
    employeeId: number | undefined
    areaId: number | undefined
  }

  // 响应式数据
  const searchForm = ref<SearchForm>({
    newPhone: '',
    employeeName: '',
    areaName: '',
    recordSolveStatus: undefined,
    createTime: undefined,
    userId: undefined,
    employeeId: undefined,
    areaId: undefined
  })

  // 用户列表（用于用户搜索选择框）
  const userList = ref<any[]>([])
  const userListLoading = ref(false)

  // 员工列表（用于员工搜索选择框）
  const employeeList = ref<any[]>([])
  const employeeListLoading = ref(false)

  // 小区列表（用于小区搜索选择框）
  const areaList = ref<any[]>([])
  const areaListLoading = ref(false)

  // 获取用户列表
  const getUserList = async (keyword = '') => {
    if (keyword && keyword.length < 2) return
    
    userListLoading.value = true
    try {
      const params = {
        current: 1,
        size: 20,
        newPhone: keyword,
        newName: keyword
      }
      
      const res = await openApiNewUserPageDataUsingPost({ body: params })
      if (res.list) {
        userList.value = res.list
      }
    } catch (error) {
      console.error('获取用户列表失败:', error)
      ElMessage.error('获取用户列表失败')
    } finally {
      userListLoading.value = false
    }
  }

  // 获取员工列表
  const getEmployeeList = async (keyword = '') => {
    if (keyword && keyword.length < 2) return
    
    employeeListLoading.value = true
    try {
      const params = {
        current: 1,
        size: 20,
        employeeName: keyword,
        employeePhone: keyword
      }
      
      const res = await apiEmployeeGetPageUsingPost({ body: params })
      if (res.list) {
        employeeList.value = res.list
      }
    } catch (error) {
      console.error('获取员工列表失败:', error)
      ElMessage.error('获取员工列表失败')
    } finally {
      employeeListLoading.value = false
    }
  }

  // 获取小区列表
  const getAreaList = async (keyword = '') => {
    if (keyword && keyword.length < 2) return
    
    areaListLoading.value = true
    try {
      const params = {
        current: 1,
        size: 20,
        areaName: keyword
      }
      
      const res = await geoAreaPageDataUsingPost({ body: params })
      if (res.list) {
        areaList.value = res.list
      }
    } catch (error) {
      console.error('获取小区列表失败:', error)
      ElMessage.error('获取小区列表失败')
    } finally {
      areaListLoading.value = false
    }
  }

  // 搜索表单配置
  const formItems = computed(() => [
    {
      key: 'userId',
      label: '用户',
      type: 'select',
      props: {
        placeholder: '请输入用户姓名或手机号搜索',
        clearable: true,
        filterable: true,
        remote: true,
        loading: userListLoading.value,
        'reserve-keyword': true,
        'remote-method': getUserList,
        options: userList.value.map((item: any) => ({
          label: `${item.newName} (${item.newPhone})`,
          value: item.id
        }))
      }
    },
    {
      key: 'employeeId',
      label: '员工',
      type: 'select',
      props: {
        placeholder: '请输入员工姓名或手机号搜索',
        clearable: true,
        filterable: true,
        remote: true,
        loading: employeeListLoading.value,
        'reserve-keyword': true,
        'remote-method': getEmployeeList,
        options: employeeList.value.map((item: any) => ({
          label: `${item.employeeName} (${item.employeePhone})`,
          value: item.id
        }))
      }
    },
    {
      key: 'areaId',
      label: '小区',
      type: 'select',
      props: {
        placeholder: '请输入小区名称搜索',
        clearable: true,
        filterable: true,
        remote: true,
        loading: areaListLoading.value,
        'reserve-keyword': true,
        'remote-method': getAreaList,
        options: areaList.value.map((item: any) => ({
          label: item.areaName,
          value: item.id
        }))
      }
    },
    {
      key: 'recordSolveStatus',
      label: '解决状态',
      type: 'select',
      props: {
        placeholder: '请选择解决状态',
        clearable: true,
        options: [
          { label: '未解决', value: '0' },
          { label: '已解决', value: '1' }
        ]
      }
    },
    {
      key: 'createTime',
      label: '创建时间',
      type: 'daterange',
      props: {
        type: 'daterange',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
        valueFormat: 'YYYY-MM-DD',
        clearable: true
      }
    }
  ])

  // 使用 useTable 管理表格数据
  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    core: {
      apiFn: pageDataApi,
      apiParams: {
        body: {
          userId: undefined,
          areaName: undefined,
          employeeName: undefined,
          recordSolveStatus: undefined,
          recordScoreStatus: undefined,
          recordTimeBegin: undefined,
          recordTimeEnd: undefined,
          newPhone: undefined,
          employeeId: undefined,
          areaId: undefined
        }
      },
      paginationWrapper: 'body',
      columnsFactory: () => [
        {
          prop: 'userName',
          label: '用户名称',
          minWidth: 100,
          formatter: (row: RecordUserAreaHelpVo) => {
            return row.userInfo?.newName || '-';
          }
        },
        {
          prop: 'userPhone',
          label: '手机号',
          minWidth: 120,
          formatter: (row: RecordUserAreaHelpVo) => {
            return row.userInfo?.newPhone || '-';
          }
        },
        {
          prop: 'recordTime',
          label: '时间',
          width: 180,
          formatter: (row: RecordUserAreaHelpVo) => {
            if (!row.recordTime) return '-'
            
            // 处理14位数字时间格式 (YYYYMMDDHHmmss)
            if (typeof row.recordTime === 'number' || /^\d{14}$/.test(row.recordTime.toString())) {
              const timeStr = row.recordTime.toString()
              const year = timeStr.substring(0, 4)
              const month = timeStr.substring(4, 6)
              const day = timeStr.substring(6, 8)
              const hour = timeStr.substring(8, 10)
              const minute = timeStr.substring(10, 12)
              const second = timeStr.substring(12, 14)
              return `${year}-${month}-${day} ${hour}:${minute}:${second}`
            }
          }
        },
        {
          prop: 'areaInfo.areaName',
          label: '小区名称',
          minWidth: 150,
          formatter: (row: RecordUserAreaHelpVo) => row.areaInfo?.areaName || '-'
        },
        {
          prop: 'employeeInfo.employeeName',
          label: '员工姓名',
          minWidth: 100,
          formatter: (row: RecordUserAreaHelpVo) => {
            return row.employeeInfo?.employeeName || '-';
          }
        },
        {
          prop: 'employeeInfo.employeePhone',
          label: '员工电话',
          minWidth: 120,
          formatter: (row: RecordUserAreaHelpVo) => {
            return row.employeeInfo?.employeePhone || '-';
          }
        },
        {
          prop: 'recordSolveStatus',
          label: '解决状态',
          minWidth: 100,
          formatter: (row: RecordUserAreaHelpVo) => {
            if (row.recordSolveStatus !== undefined && row.recordSolveStatus !== null) {
              return h(DictTag, {
                dictType: '10210',
                value: row.recordSolveStatus
              })
            }
            return '-'
          }
        },
        {
          prop: 'recordScoreStatus',
          label: '评价',
          minWidth: 100,
          formatter: (row: RecordUserAreaHelpVo) => {
            if (row.recordScoreStatus !== undefined && row.recordScoreStatus !== null) {
              return h(DictTag, {
                dictType: '10200',
                value: row.recordScoreStatus
              })
            }
            return '-'
          }
        },
        {
          prop: 'operation',
          label: '操作',
          width: 150,
          fixed: 'right',
          align: 'center',
          headerAlign: 'center',
          useSlot: true
        }
      ]
    }
  })

  const showSearchBar = ref(true)
  const detailVisible = ref(false)
  const currentRow = ref<RecordUserAreaHelpVo | null>(null)
  const dialogKey = ref(0)

  const handleSearch = () => {
    // 更新搜索参数
    searchParams.body.newPhone = searchForm.value.newPhone || undefined;
    searchParams.body.employeeName = searchForm.value.employeeName || undefined;
    searchParams.body.areaName = searchForm.value.areaName || undefined;
    searchParams.body.recordSolveStatus = searchForm.value.recordSolveStatus || undefined;
    searchParams.body.userId = searchForm.value.userId || undefined;
    searchParams.body.employeeId = searchForm.value.employeeId || undefined;
    searchParams.body.areaId = searchForm.value.areaId || undefined;
    
    // 处理时间范围
    if (searchForm.value.createTime && searchForm.value.createTime.length === 2) {
      searchParams.body.recordTimeBegin = searchForm.value.createTime[0];
      searchParams.body.recordTimeEnd = searchForm.value.createTime[1];
    } else {
      searchParams.body.recordTimeBegin = undefined;
      searchParams.body.recordTimeEnd = undefined;
    }    
    // 调用 getData 获取数据
    getData();
  }

  const handleResetSearch = () => {
    searchForm.value.newPhone = ''
    searchForm.value.employeeName = ''
    searchForm.value.areaName = ''
    searchForm.value.recordSolveStatus = undefined
    searchForm.value.createTime = undefined
    searchForm.value.userId = undefined
    searchForm.value.employeeId = undefined
    searchForm.value.areaId = undefined
    
    // 重置 searchParams
    searchParams.body.newPhone = undefined;
    searchParams.body.employeeName = undefined;
    searchParams.body.areaName = undefined;
    searchParams.body.recordSolveStatus = undefined;
    searchParams.body.recordTimeBegin = undefined;
    searchParams.body.recordTimeEnd = undefined;
    searchParams.body.userId = undefined;
    searchParams.body.employeeId = undefined;
    searchParams.body.areaId = undefined;
    searchParams.body.current = 1;
    
    // 重置后重新获取数据
    getData();
  }

  const handleView = async (row: RecordUserAreaHelpVo) => {
    try {
      currentRow.value = null
      detailVisible.value = true
      
      const res = await getDataApi({
        body: {
          id: row.id
        }
      })
      
      if (res && typeof res === 'object' && Object.keys(res).length > 0) {
        currentRow.value = res
      } else {
        detailVisible.value = false
        ElMessage.warning('未找到相关数据')
      }
    } catch (err) {
      ElMessage.error('获取详情失败: ' + (err.message || '未知错误'))
      detailVisible.value = false
    }
  }

  const handleDialogUpdate = (val: boolean) => {
    detailVisible.value = val;
  }
</script>

<style lang="scss" scoped>
</style>